import React, { useState, useEffect } from 'react'
import { Card, Button, Space, message, Image, Form, Input, Select, Row, Col, Modal, Upload } from 'antd'
import { useNavigate } from 'react-router-dom'
import { PlusOutlined, DeleteOutlined, ExportOutlined, ImportOutlined, EditOutlined, UploadOutlined } from '@ant-design/icons'
import type { UploadProps } from 'antd'
import MyTable from '@/components/MyTable'
import { getProductList, deleteProduct, batchDeleteProduct, exportProduct } from '@/api/product'
import ProductAddDialog from './ProductAddDialog'

// 定义产品接口
interface ProductType {
  id: number
  teamId: number
  categoryId: number
  productTypeId: number
  productName: string
  sku: string
  specification: string
  purchasePrice: number
  sellingPrice: number
  stockAlert: number
  weight: number
  brand: string
  model: string
  englishName: string
  customsCode: string
  declaredPrice: number
  length: number
  width: number
  height: number
  status: number
  notes: string
  photo: string
}

// 定义查询参数接口
interface QueryParams {
  pageIndex: number
  pageSize: number
  productName?: string
  sku?: string
  productTypeId?: number
  categoryId?: number
}

// 定义API响应接口
interface ApiResult<T> {
  code: number
  message: string
  data: T
  isSuc: boolean
}

interface PagingResult<T> {
  data: T
  total: number
  pageIndex: number
  pageSize: number
}

const Product: React.FC = () => {
  const navigate = useNavigate()
  const [loading, setLoading] = useState<boolean>(false)
  const [productList, setProductList] = useState<ProductType[]>([])
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const [queryParams, setQueryParams] = useState<QueryParams>({
    pageIndex: 1,
    pageSize: 10
  })
  const [form] = Form.useForm()
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [isAddModalVisible, setIsAddModalVisible] = useState<boolean>(false)
  const [currentProduct, setCurrentProduct] = useState<ProductType | null>(null)
  const [importModalVisible, setImportModalVisible] = useState<boolean>(false)

  // 定义表格列
  const columns = [
    {
      title: '产品图片',
      dataIndex: 'photo',
      key: 'photo',
      render: (photo: string) => (
        photo ? (
          <Image 
            src={`http://localhost:23892${photo}`} 
            alt="产品图片" 
            width={50} 
            height={50}
          />
        ) : '无图片'
      )
    },
    {
      title: '产品ID',
      dataIndex: 'id',
      key: 'id'
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName'
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      key: 'sku'
    },
    {
      title: '规格',
      dataIndex: 'specification',
      key: 'specification'
    },
    {
      title: '品牌',
      dataIndex: 'brand',
      key: 'brand'
    },
    {
      title: '型号',
      dataIndex: 'model',
      key: 'model'
    },
    {
      title: '产品类型',
      dataIndex: 'productTypeId',
      key: 'productTypeId',
      render: (typeId: number) => {
        const typeMap = {
          1: '普通商品',
          2: '组合商品'
        };
        return typeMap[typeId as keyof typeof typeMap] || '未知类型';
      }
    },
    {
      title: '产品分类',
      dataIndex: 'categoryId',
      key: 'categoryId',
      render: (categoryId: number) => {
        const categoryMap = {
          1: '电子产品',
          2: '生活用品',
          3: '床上用品'
        };
        return categoryMap[categoryId as keyof typeof categoryMap] || '未知分类';
      }
    },
    {
      title: '入库价格',
      dataIndex: 'purchasePrice',
      key: 'purchasePrice',
      render: (price: number) => `¥${(price / 100).toFixed(2)}`
    },
    {
      title: '出库价格',
      dataIndex: 'sellingPrice',
      key: 'sellingPrice',
      render: (price: number) => `¥${(price / 100).toFixed(2)}`
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (status === 1 ? '启用' : '禁用')
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (_: any, record: ProductType) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button 
            type="primary" 
            onClick={() => handlePrintLabel(record.id)}
          >
            打印标签
          </Button>
          <Button 
            danger
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ]

  // 获取产品列表
  const fetchProductList = async (params: QueryParams) => {
    setLoading(true)
    try {
      const res = await getProductList(params) as ApiResult<PagingResult<ProductType[]>>
      
      if (res.isSuc && res.data) {
        setProductList(res.data.data || [])
        setPagination({
          ...pagination,
          current: params.pageIndex,
          total: res.data.total || 0
        })
      } else {
        message.error(res.message || '获取产品列表失败')
      }
    } catch (error) {
      console.error('获取产品列表失败:', error)
      message.error('获取产品列表失败')
    } finally {
      setLoading(false)
    }
  }

  // 处理分页变化
  const handleTableChange = (page: number, pageSize?: number) => {
    const newParams = {
      ...queryParams,
      pageIndex: page,
      pageSize: pageSize || queryParams.pageSize
    }
    setQueryParams(newParams)
    fetchProductList(newParams)
  }

  // 处理查询
  const handleSearch = () => {
    const values = form.getFieldsValue()
    const newParams = {
      ...queryParams,
      ...values,
      pageIndex: 1 // 重置到第一页
    }
    setQueryParams(newParams)
    fetchProductList(newParams)
  }

  // 重置查询条件
  const handleReset = () => {
    form.resetFields()
    const newParams = {
      pageIndex: 1,
      pageSize: 10
    }
    setQueryParams(newParams)
    fetchProductList(newParams)
  }

  // 处理添加产品
  const handleAdd = () => {
    setCurrentProduct(null)
    setIsAddModalVisible(true)
  }

  // 处理编辑产品
  const handleEdit = (record: ProductType) => {
    setCurrentProduct(record)
    setIsAddModalVisible(true)
  }

  // 处理删除产品
  const handleDelete = (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个产品吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await deleteProduct(id) as ApiResult<any>
          if (res.isSuc) {
            message.success('删除成功')
            fetchProductList(queryParams)
          } else {
            message.error(res.message || '删除失败')
          }
        } catch (error) {
          console.error('删除产品失败:', error)
          message.error('删除产品失败')
        }
      }
    })
  }

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的产品')
      return
    }

    Modal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个产品吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await batchDeleteProduct(selectedRowKeys as number[]) as ApiResult<any>
          if (res.isSuc) {
            message.success('批量删除成功')
            setSelectedRowKeys([])
            fetchProductList(queryParams)
          } else {
            message.error(res.message || '批量删除失败')
          }
        } catch (error) {
          console.error('批量删除产品失败:', error)
          message.error('批量删除产品失败')
        }
      }
    })
  }

  // 处理导出产品
  const handleExport = async () => {
    try {
      const values = form.getFieldsValue()
      const params = {
        ...values
      }
      
      const res = await exportProduct(params) as Blob
      
      // 创建Blob对象并下载
      const url = window.URL.createObjectURL(res)
      const link = document.createElement('a')
      link.href = url
      link.download = '产品列表.xlsx'
      link.click()
      window.URL.revokeObjectURL(url)
      
      message.success('导出成功')
    } catch (error) {
      console.error('导出产品失败:', error)
      message.error('导出产品失败')
    }
  }

  // 处理导入产品
  const handleImport = () => {
    setImportModalVisible(true)
  }

  // 导入文件上传配置
  const importProps: UploadProps = {
    name: 'file',
    action: 'http://localhost:23892/api/Products/ImportProduct',
    headers: {
    },
    onChange(info) {
      if (info.file.status === 'done') {
        if (info.file.response.isSuc) {
          message.success(`${info.file.name} 导入成功`);
          setImportModalVisible(false)
          fetchProductList(queryParams)
        } else {
          message.error(`${info.file.name} 导入失败: ${info.file.response.message}`);
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 导入失败`);
      }
    },
  };

  // 处理打印标签按钮点击
  const handlePrintLabel = (id: number) => {
    // 导航到标签打印页面，并传递产品ID
    navigate(`/product/label/${id}`)
  }

  // 处理添加/编辑对话框确认
  const handleAddDialogOk = () => {
    setIsAddModalVisible(false)
    fetchProductList(queryParams)
  }

  // 处理添加/编辑对话框取消
  const handleAddDialogCancel = () => {
    setIsAddModalVisible(false)
  }

  useEffect(() => {
    fetchProductList(queryParams)
  }, [])

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: React.Key[]) => {
      setSelectedRowKeys(keys)
    }
  }

  return (
    <Card title="产品列表">
      <Form
        form={form}
        layout="inline"
        style={{ marginBottom: 16 }}
      >
        <Row gutter={16} style={{ width: '100%', marginBottom: 16 }}>
          <Col span={6}>
            <Form.Item name="productName" label="产品名称">
              <Input placeholder="请输入产品名称" allowClear />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="sku" label="SKU">
              <Input placeholder="请输入SKU" allowClear />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="productTypeId" label="产品类型">
              <Select
                placeholder="请选择产品类型"
                allowClear
                options={[
                  { value: 1, label: '普通商品' },
                  { value: 2, label: '组合商品' }
                ]}
              />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="categoryId" label="产品分类">
              <Select
                placeholder="请选择产品分类"
                allowClear
                options={[
                  { value: 1, label: '电子产品' },
                  { value: 2, label: '生活用品' },
                  { value: 3, label: '床上用品' }
                ]}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16} style={{ width: '100%' }}>
          <Col span={24} style={{ textAlign: 'right' }}>
            <Space>
              <Button type="primary" onClick={handleSearch}>查询</Button>
              <Button onClick={handleReset}>重置</Button>
            </Space>
          </Col>
        </Row>
      </Form>

      <div style={{ marginBottom: 16 }}>
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>添加产品</Button>
          <Button danger icon={<DeleteOutlined />} onClick={handleBatchDelete} disabled={selectedRowKeys.length === 0}>
            批量删除
          </Button>
          <Button icon={<ImportOutlined />} onClick={handleImport}>导入</Button>
          <Button icon={<ExportOutlined />} onClick={handleExport}>导出</Button>
        </Space>
      </div>

      <MyTable
        columns={columns}
        dataSource={productList}
        loading={loading}
        rowSelection={rowSelection}
        rowKey="id"
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          onChange: handleTableChange
        }}
      />

      {/* 添加/编辑产品对话框 */}
      {isAddModalVisible && (
        <ProductAddDialog
          visible={isAddModalVisible}
          product={currentProduct}
          onOk={handleAddDialogOk}
          onCancel={handleAddDialogCancel}
        />
      )}

      {/* 导入产品对话框 */}
      <Modal
        title="导入产品"
        open={importModalVisible}
        onCancel={() => setImportModalVisible(false)}
        footer={null}
      >
        <p>请选择Excel文件进行导入：</p>
        <Upload.Dragger {...importProps}>
          <p className="ant-upload-drag-icon">
            <UploadOutlined />
          </p>
          <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p className="ant-upload-hint">支持单个或批量上传，仅支持 .xlsx 和 .xls 格式</p>
        </Upload.Dragger>
      </Modal>
    </Card>
  )
}

export default Product